package club.qwertyzzz;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.awt.*;

@AllArgsConstructor
@NoArgsConstructor
public class Bullet {
    public static final int speed = 5;
    public static final int WIDTH = ResourceMgr.tankMissile.getWidth();
    public static final int HEIGHT = ResourceMgr.tankMissile.getHeight();
    private int x, y;
    private Dir dir;
    private TankFrame tankFrame = null;
    private Tank tank;

    @Getter
    private boolean living = true;

    // 代表子弹的矩形
    private Rectangle rectangle = null;

    public Bullet(int x, int y, Dir dir, TankFrame tankFrame, Tank tank) {
        this.x = x;
        this.y = y;
        this.dir = dir;
        this.tankFrame = tankFrame;
        this.tank = tank;
    }

    /**
     * 画出子弹自身
     * @param g 系统提供的画笔
     */
    public void paint(Graphics g) {
        if(!living)
            return;
        g.drawImage(ResourceMgr.tankMissile, x, y, null);
        move();
    }

    /**
     * 子弹按照自己的发射方向移动
     */
    public void move() {
        switch(dir) {
            case LEFT:
                x -= speed;
                break;
            case RIGHT:
                x += speed;
                break;
            case UP:
                y -= speed;
                break;
            case DOWN:
                y += speed;
                break;
        }

        // 超出边界的子弹需要被删除掉
        if(x < 0 || y < 0 || x > tankFrame.GAME_WIDTH || y > tankFrame.GAME_HEIGHT) {
            die();
        }
    }

    /**
     * 如果当前子弹和参数坦克发生了碰撞，则坦克和子弹均销毁。
     * 同一阵营的坦克和子弹不销毁
     * @param tank
     */
    public void coordinateWith(Tank tank) {

        // 子弹 和 坦克同一个阵营则不销毁
        boolean isEnemyTank = tank.getType().isEnemyTank();
        boolean isEnemyBullet = isEnemyBullet();
        if(isEnemyTank == isEnemyBullet) {
            return;
        }

        Rectangle bulletRect = rect();
        Rectangle tankRect = tank.rect();
        if(bulletRect.intersects(tankRect)) {
            tank.die();
            this.die();
        }
    }

    /**
     * 销毁子弹：即从TankFrame的子弹队列当中移除子弹
     */
    public void die() {
        living = false;
        tankFrame.getBullets().remove(this);
    }

    /**
     * 根据 聚合的坦克的类型的阵营判断子弹的阵营
     * @return
     */
    private boolean isEnemyBullet() {
        return tank.getType().isEnemyTank();
    }

    /**
     * 获取子弹的代表的矩形
     * @return
     */
    public Rectangle rect() {
        if(rectangle == null) {
            rectangle = new Rectangle(x, y, WIDTH, HEIGHT);
        } else {
            rectangle.x = x;
            rectangle.y = y;
            rectangle.width = WIDTH;
            rectangle.height = HEIGHT;
        }
        return rectangle;
    }
}
